package com.iflytek.autofly.setting.biz.display;

import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.ToggleButton;

import com.iflytek.autofly.displayservice.util.DisplayManager;
import com.iflytek.autofly.displayservice.util.DisplayServiceCons;
import com.iflytek.autofly.displayservice.util.IDisplayListener;
import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.base.BaseFragment;
import com.iflytek.autofly.setting.util.FlySettings;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.sunflower.FlowerCollector;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <b>Description: </b>声音设置的fragment<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015年10月14日</td>
 * <td>上午11:34:14</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public class DisplayFragment extends BaseFragment implements IDisplayListener {
    protected static final String TAG = "DisplayFragment";

    private static final String[] CMD = {"brightness", "autobrightness"};

    private static final String PROPERTY_AUTOBRIGHTNESS = "persist.sys.autofly.auto_bright";

    private AtomicInteger mServiceReady = new AtomicInteger(0);
    private SeekBar mBrightnessSb;

    private DisplayManager mDisplay;
    private int mBrightnessMin;
    private ToggleButton mAutoBrightnessTbn;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        init(view);
        return view;
    }

    @Override
    public void onDestroyView() {
        if (mDisplay != null) {
            synchronized (this) {
                DisplayManager.unregisterListener(this);
                mDisplay = null;
            }
        }
        mServiceReady.set(0);
        super.onDestroyView();
    }

    private void init(View v) {
        addUnit(R.layout.brightness);
        addUnit(R.layout.autobrightness);
        mBrightnessSb = (SeekBar) v.findViewById(R.id.display_brightness_sb);
        mBrightnessSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public boolean mTouched = false;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mTouched) {
                    FlyLog.d(TAG, "setBrightness " + (progress + mBrightnessMin));
                    mDisplay.setBrightness(progress + mBrightnessMin);
                    Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_CUR, progress + mBrightnessMin);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mTouched = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.display) + "-" + getString(R.string.display_brightness), "" + (mBrightnessSb.getProgress() + mBrightnessMin));
                mTouched = false;
            }
        });
        mAutoBrightnessTbn = (ToggleButton) v.findViewById(R.id.display_autobrightness_switch_tbn);
        mAutoBrightnessTbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.display) + "-" + getString(R.string.display_autobrightness), "" + isChecked);
                setAutoBrightnessEnableState(isChecked);
                Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_AUTO, isChecked ? 1 : 0);
                //mDisplay.setAutoBrightnessEnable(isChecked);
            }
        });
        mAutoBrightnessTbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        mDisplay = DisplayManager.registerListener(getActivity(), this);
    }

    public void renew() {
        if (mServiceReady.incrementAndGet() < 3) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int brightnessRange, brightness;
                            if (mDisplay != null) {
                                DisplayManager display = mDisplay;
                                mBrightnessMin = display.getBrightnessMin();
                                Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_MIN, mBrightnessMin);
                                brightnessRange = display.getBrightnessMax() - mBrightnessMin;
                                Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_MAX, display.getBrightnessMax());
                                brightness = display.getBrightness();
                                Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_CUR, brightness);
                            } else {
                                mBrightnessMin = Settings.Global.getInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_MIN, 0);
                                brightnessRange = Settings.Global.getInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_MAX, 20) - mBrightnessMin;
                                brightness = Settings.Global.getInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_CUR, 20);
                            }

                            final boolean autoBrightnessEnabled = getAutoBrightnessEnableState();
                            FlyLog.d(TAG, "brightness=" + brightness + ",autoBrightnessEnabled=" + autoBrightnessEnabled);

                            if (brightness >= mBrightnessMin) {
                                mBrightnessSb.setMax(brightnessRange);
                                mBrightnessSb.setProgress(brightness - mBrightnessMin);
                            }
                            mAutoBrightnessTbn.setChecked(autoBrightnessEnabled);
                        }
                    });
                }
            }
        }).start();
    }

    private boolean getAutoBrightnessEnableState() {
        if (mDisplay != null) {
            return mDisplay.getAutoBrightnessEnableState() == 1;
        }
        FlyLog.e(TAG, "sevice not ready");
        return Settings.Global.getInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_AUTO, 1) == 1;
        //return SystemProperties.getBoolean(PROPERTY_AUTOBRIGHTNESS, true);
    }

    private void setAutoBrightnessEnableState(boolean isEnabled) {
        if (isEnabled != getAutoBrightnessEnableState()) {
            if (mDisplay != null) {
                FlyLog.d(TAG, "AutoBrightness=" + isEnabled);
                mDisplay.setAutoBrightnessEnable(isEnabled);
            }
        }
    }

    @Override
    public void processCommandline(String cmd) {

    }

    @Override
    public String[] getCommands() {
        return CMD;
    }

    @Override
    public void onServiceStatusChanged(int status) {
        switch (status) {
            case DisplayServiceCons.AidlStatus.SERVICE_AIDL_BOUND:
                FlyLog.d(TAG, "SERVICE_AIDL_BOUND");
                renew();
                break;

            case DisplayServiceCons.AidlStatus.SERVICE_AIDL_NOT_BOUND:
                FlyLog.e(TAG, "SERVICE_AIDL_NOT_BOUND");
                break;
        }
    }

    @Override
    public void onBrightnessChanged(final int value) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mBrightnessSb.setProgress(value - mBrightnessMin);
            }
        });
        Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_CUR, value);
    }

    @Override
    public void onAutoBrightnessChanged(final int value) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAutoBrightnessTbn.setChecked(value == 1);
            }
        });
        Settings.Global.putInt(getActivity().getContentResolver(), FlySettings.Display.BRIGHTNESS_AUTO, value);
    }
}
